const axios = require('axios');
const proxyConfig = require('../../config/proxy.config');

// 创建axios实例
const instance = axios.create({
  timeout: 10000,
  headers: {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
  }
});

// 配置代理
if (proxyConfig.enabled) {
  instance.defaults.proxy = {
    host: proxyConfig.host,
    port: proxyConfig.port,
    ...(proxyConfig.auth && { auth: proxyConfig.auth })
  };
}

// 重试拦截器
instance.interceptors.response.use(
  response => response,
  error => {
    const { config } = error;
    if (!config || !config.retry) return Promise.reject(error);
    
    config.retryCount = config.retryCount || 0;
    
    if (config.retryCount >= config.retry) {
      return Promise.reject(error);
    }
    
    config.retryCount += 1;
    const backoff = new Promise(resolve => {
      setTimeout(() => resolve(), config.retryDelay || 1000);
    });
    
    return backoff.then(() => instance(config));
  }
);

async function fetchPage(url) {
  try {
    const response = await instance.get(url);
    return response.data;
  } catch (error) {
    console.error(`获取页面失败: ${url}`, error.message);
    throw error;
  }
}

module.exports = {
  fetchPage
};  